using System.IO;
using BitTorrent.Client.Peer.Exceptions;

namespace BitTorrent.Client.Peer.Message.Standard {
    /// <summary>
    /// Class representing a peer request message, used to request a block.
    /// </summary>
    internal class Request : PeerMessage
    {
        public Request() {
            Length = Begin = Length = -1;
        }

        public Request(BinaryReader reader) {
            Contruct(reader);
        }

        #region Properties

        public int Index { get; set; }

        public int Begin { get; set; }

        public int Length { get; set; }

        #endregion

        public override byte[] GetMessage() {
            return GetMessage(PeerMessageId.Request, 17);
        }

        protected byte[] GetMessage(PeerMessageId peerMessageId, int size) {
            var result = new byte[size];

            using (var memory = new MemoryStream(result)) {
                var writer = new BinaryWriter(memory);

                /// Length (fixed)
                writer.Write(ToBytes(size - 4)); /// Allways subtract 4 that is the init length
                writer.Write((byte)peerMessageId);

                if (Length < 0 || Begin < 0 || Index < 0) {
                    throw new PeerMessageException("Invalid property values for request.");
                }

                writer.Write(ToBytes(Index));
                writer.Write(ToBytes(Begin));
                writer.Write(ToBytes(Length));

                writer.Flush();
            }

            return result;
        }

        private void Contruct(BinaryReader reader) {
            Index = ReadInt32(reader);
            Begin = ReadInt32(reader);
            Length = ReadInt32(reader);
        }
    }
}